package com.ycz.algorithm.utils.queue;

/**
 * @author yancz
 * @ClassName ArrayQueue
 * @description: 基于数组实现的队列
 * @date 2024-11-26 17:04:02
 * @version: 1.0
 */
public class ArrayQueue {

    private int[] nums; // 存储队列元素的数组

    private int front; // 队首指针，指向队首元素

    private int queueSize; // 队列长度

    // 队列初始化
    public ArrayQueue(int capacity) {
        nums = new int[capacity];
        front = queueSize = 0;
    }

    // 获取队列容量
    public int capacity() {
        return nums.length;
    }

    // 获取队列长度
    public int size() {
        return queueSize;
    }

    // 判断队空
    public boolean isEmpty() {
        return queueSize == 0;
    }

    // 入队
    public void push(int num) {
        if (queueSize == capacity()) {
            System.out.println("队列已满！");
            return;
        }
        // 计算队尾指针，元素入队，指向队尾索引+1
        // 取余操作实现rear越过数组尾部后回到头部
        int rear = (front + queueSize) % capacity();
        nums[rear] = num;
        queueSize++;
    }

    // 出队
    public int pop() {
        int num = peek();
        // 队首指针后移一位，若越过尾部，则回到头部
        front = (front + 1) % capacity();
        queueSize--;
        return num;
    }

    // 访问队首元素
    public int peek() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("队空！");
        }
        return nums[front];
    }

    // 转为数组
    public int[] toArray() {
        int[] res = new int[queueSize];
        for (int i = 0, j = front; i < queueSize; i++, j++) {
            res[i] = nums[j % capacity()];
        }
        return res;
    }

    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(5);
        // 入队
        arrayQueue.push(1);
        arrayQueue.push(2);
        arrayQueue.push(3);
        arrayQueue.push(4);
        commonPrint(arrayQueue);
        arrayQueue.push(5);
        arrayQueue.push(6);
        commonPrint(arrayQueue);
        // 出队
        System.out.println("出队元素：" + arrayQueue.pop());
        commonPrint(arrayQueue);
    }

    public static void commonPrint(ArrayQueue arrayQueue) {
        int[] res = arrayQueue.toArray();
        for (int i : res) {
            System.out.print(i + "\t");
        }
        System.out.println();
        System.out.println("队列容量：" + arrayQueue.capacity());
        System.out.println("队列长度：" + arrayQueue.queueSize);
        System.out.println("队首元素：" + arrayQueue.peek());
    }

}
